/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dk.itu.samd.group2.tagapastry;

import java.io.IOException;

import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import java.util.concurrent.atomic.AtomicInteger;
/**
 *
 * @author frgr
 */
public class IndexEntryImpl implements IndexEntry {

  public IndexEntryImpl(String content, String hash) {
    this.content = content;
    this.incrementRank();
    setHash(hash);
  }
  
  public IndexEntryImpl(InputBuffer buf) throws IOException {
	  this.content = buf.readUTF();
	  rank = new AtomicInteger( buf.readInt() );
	  setHash(buf.readUTF());
  }

  public void decrementRank() {
	  rank.decrementAndGet();
  }

  public void incrementRank() {
	  rank.incrementAndGet();
  }

  public int compareTo(IndexEntry ie) {
    return this.rank.get() - ie.getRank();
  }

  public String getContent() {
    return content;
  }

  public int getRank() {
    return rank.get();
  }
  
  public String getHash() {
	  return hash;
  }
  
  public void setHash(String hash) {
	  this.hash = hash;
  }

  public String toString() {
    return "{entry: " + this.content + ", rank: " + this.rank + ", hash: " + this.getHash() + "} ";
  }
  
  @Override
  public void serialize(OutputBuffer buf) throws IOException {
  	 buf.writeUTF(content);
  	 buf.writeInt(rank.get());
  	 buf.writeUTF(getHash());
  }
  
  private String content;
//  private int rank = 0;
  private AtomicInteger rank = new AtomicInteger(0);
  
  // Adding also hash value. There may be a situation where
  // we want to store 2 different objects using the same name.
  // Hash value will help us differentiate between them.
  private String hash;

	@Override
	public int getSize() {
		return content.length() + hash.length() + 4;
	}

}
